import { sliceUploadFile } from "@/apis/file";
import { closeMessage, openMessage } from "@/hy_dev_lib/src";
import { openModal } from "@/hy_dev_lib/src/components/useModal";
import { AnyObject } from "antd/es/_util/type";
import { BYTES_PER_SLICE, MAX_FILE_SIZE } from "./const";

/**
 * @param {上传文件} file
 * @param {保存的文件夹} saveFolder
 * @param {当前片数} index
 * @returns
 */
export const sliceUpload = (
  file: any,
  saveFolder: string,
  index: number = 0,
  extraParams?: AnyObject
): any => {
  if (file.size == 0) {
    openMessage({
      type: "warning",
      content: "请上传有效文件!",
    });
    return Promise.reject("size 为0");
  }
  if (file.size > MAX_FILE_SIZE) {
    openMessage({
      type: "warning",
      content: "上传文件大小限1GB，当前文件过大，请拆分上传！",
    });
    return Promise.reject("size 过大");
  }

  let fileName = file.name; // 文件名
  let totalSlices = Math.ceil(file.size / BYTES_PER_SLICE); // 计算文件切片总数(向上取整)

  if (index >= totalSlices) {
    return;
  }

  let start = index * BYTES_PER_SLICE; // 分片的开始
  let end = start + BYTES_PER_SLICE; // 分片的结束（不含）
  var slice = file.slice(start, end); //切割文件

  const data = {
    filepathname: saveFolder,
    data: slice,
    lastModified: file.lastModified,
    total: totalSlices,
    fileName: fileName,
    filesize: file.size,
    // suffix: suffix,
    index: index,
    ...extraParams,
  };
  openMessage({
    type: "loading",
    content: "加载中...",
    key: "FILE_UPLOAD_LOADING",
    duration: 0,
  });
  openModal();
  // 不断循环将切片上传
  return sliceUploadFile(data)
    .then((result) => {
      if (index + 1 == totalSlices) {
        closeMessage("FILE_UPLOAD_LOADING");
        openModal();
        // Modal.destroyAll();
        return Promise.resolve(result);
      } else {
        return sliceUpload(file, saveFolder, index + 1);
      }
      // } else {
      //   message.error(result.result)
      //   return Promise.resolve(result)
      // }
    })
    .catch((err) => {
      closeMessage("FILE_UPLOAD_LOADING");
      openModal();
      // Modal.destroyAll();
      // loadingModal.destroy()
      // 需要解析的文件使用弹窗提示
      // if (needAnalysis) {
      //   dispatchPubsub("SHOW_TIPS_MODAL", {
      //     type: "error",
      //     content: "上传失败，请重试",
      //     title: "提示",
      //     inoperable: true,
      //   } as ITipsModalProps);
      // } else {
      //   openMessage({
      //     type: "error",
      //     content: "上传失败，请重试",
      //   })
      // }
      return Promise.reject(err);
    });
};
